const fs = require('fs');
const path = require('path');
const fsutil = require('./lib/fsutil');
const xmljs = require('./lib/xml')

const resMap = {};
const itemRendererMap = {};

const NODE_MAP = {
    Image:"Image",
    List:"List",
    Panel:"Panel",
	Group:"Group",
	layout:"layout",
	ArrayCollection:"ArrayCollection",
    Range:"Range",
    Button:"Button",
    CheckBox:"CheckBox",
    RadioButton:"RadioButton",
    RadioButtonGroup:"RadioButtonGroup",
    ToggleButton:"ToggleButton",
    ToggleSwitch:"ToggleSwitch",
    BitmapLabel:"BitmapLabel",
    TextInput:"TextInput",
    Label:"Label",
    EditableText:"EditableText",
    TileLayout:"TileLayout",
    VerticalLayout:"VerticalLayout",
    HorizontalLayout:"HorizontalLayout",
    HScrollBar:"HScrollBar",
    VScrollBar:"VScrollBar",
    HSlider:"HSlider",
    VSlider:"VSlider",
    Rect:"Rect",
    ProgressBar:"ProgressBar",
    DataGroup:"DataGroup",
    RowAlign:"RowAlign",
    Scroller:"Scroller",
    TabBar:"TabBar",
    skinName:"skinName"
};

module.exports = function(source, target, egretSheet, callback){
	addResInfo(egretSheet);

	let fileList = [];
	fsutil.travel(source, fileList);
	fileList = fileList.filter((name)=>{return name.indexOf("_") != 0});

	let itemRendererList = fileList.filter((name)=>{return name.indexOf("ItemRenderer") > 0});
	let skinList = fileList.filter((name)=>{return name.indexOf("ItemRenderer") < 0});

	addItemSkin(itemRendererList);
	addSkin(skinList, target)
}

// 添加资源
function addResInfo(source) {
	let list = fs.readdirSync(source);
	for (let i = 0; i < list.length; i++) {
		let file = list[i];
		let json = JSON.parse(fs.readFileSync(path.join(source, file), "utf8"));
		let frames = json.frames;
		Object.assign(resMap, frames);
	}
}

// 因为itemrenderer可能被共享
function addItemSkin(fileList) {
	console.log("itemrenderer皮肤文件数量:", fileList.length);
	for (let i = 0, len = fileList.length; i < len; i++) {
		let result = generateJSONByExml(fileList[i])
		let out = {};
		let name = path.basename(fileList[i]);
		name = name.replace(/\.\w+/, "");
		out.name = name;
		parseObj(result, out)
		itemRendererMap[name] = result;
	}
}

function addSkin(fileList, target) {
	let skinObj = {};
	console.log("皮肤文件数量:", fileList.length);
	for (let i = 0, len = fileList.length; i < len; i++) {
		let result = generateJSONByExml(fileList[i])
		let out = {};
		let name = path.basename(fileList[i]);
		name = name.replace(/\.\w+/, "");
		out.name = result.$class;
		parseObj(result, out);
		if (!skinObj[name]) {
			skinObj[name] = out;
		} else {
			console.error("皮肤名不能重复的");
		}
		delete out.class;
		let skinStr = JSON.stringify(out, null, 2)
		fs.writeFileSync(path.join(target, name + ".json"), skinStr)
	}
	let jsonStr = JSON.stringify(skinObj, null, 2);
	fs.writeFileSync(path.join(target, "all.json"), jsonStr);
}

// 通过exml生成json
function generateJSONByExml(file) {
	let str = fs.readFileSync(file);
	let headStart = str.indexOf("<?xml");
	let headEnd = str.indexOf(">");
	if (headStart >= 0 && headEnd >= 0) {
		str = str.slice(headEnd + 1)
	}
	let result = xmljs.parse(str);
	return result;
}

function parseObj(obj, out) {
	let name = getNodeName(obj)
	copyCommonProp(obj.attributes, out)
	if (name == "Label") {
		createLabel(obj.attributes, out);
	} else if (name == "Button") {
		createButton(obj.attributes, out)
	} else if (name == "Image" || name == "BImage") {
		createBitmap(obj.attributes, out);
	} else if (name == "ProgressBar") {
		createProgressBar(obj.attributes, out);
	} else if (name == "Scroller") {
		createScroller(obj, out);
	} else if (name == "List") {
		createList(obj, out);
	} else if (name == "Group" || name == "BGroup" || name == "Skin") {
		out.node = name;
		for (let i = 0, len = obj.children ? obj.children.length : 0; i < len; i++) {
			if (!out["children"]) {
				out["children"] = [];
			}
			let childObj = parseObj(obj["children"][i], {});
			out["children"].push(childObj);
		}
	} 
	else {
		console.log(`类:${name}还未添加`)
	}
	return out;
}

function createButton(attributes, out) {

}

// 创建label
function createLabel(attributes, out) {
	out.node = "Label";
	let style = {};
	if (attributes.text) {
		out.text = attributes.text;
	}
	out.x = attributes.x || 0;
	out.y = attributes.y || 0;
	if (attributes.size) {
		style.fontSize = +attributes.size;
	}
	if (attributes.stroke) {
		style.strokeThickness = +attributes.stroke;
	}
	if (attributes.strokeColor) {
		style.stroke = attributes.strokeColor;
	}
	if (attributes.fontFamily) {
		style.fontFamily = attributes.fontFamily;
	}
	if (attributes.textAlign) {
		style.align = attributes.textAlign;
	}
	if (attributes.textColor) {
		style.fill = attributes.textColor;
	}
	out.style = style;
	return out;
}

// 创建bitmap
function createBitmap(attributes, out) {
	let info = resMap[attributes.source];
	if (attributes.scale9Grid) {
		var arr = attributes.scale9Grid.split(",");
		if (resMap[attributes.source]) {
			out.node = "Image9";
			let scale9Left = +arr[0];
			let scale9Top = +arr[1];
			let scale9Right = +arr[2];
			let scale9Bottom = +arr[3];
			scale9Right = info.sourceW - scale9Left - scale9Right;
			scale9Bottom = info.sourceH - scale9Top - scale9Bottom;
			out.scale9 = [scale9Left, scale9Top, scale9Right, scale9Bottom]
		} else {
			out.node = "Image";
			out.src = attributes.source.replace("_png", ".png")
			console.error("没有定义资源:", attributes.source)
		}
	}
	if (attributes.source) {
		out.node = "Image";
		out.src = attributes.source.replace("_png", ".png")
	}
}

// 创建进度条
function createProgressBar(attributes, out) {
	out.node = "ProgressBar";
	
}

// 创建scroller
function createScroller(obj, out) {
	out.node = "Scroller";
	if (obj.children) {
		let item = parseObj(obj.children[0], {});
		out.target = item;
	}
}

// 创建list
function createList(obj, out) {
	out.node = "List";
	let count = obj.children ? obj.children.length : 0;
	for (let i = 0; i < count; i++) {
		let item = obj.children[i];
		let name = getNodeName(item);
		if (name == "layout") {
			out.layout = createLayout(item)
		} else if (name == "ArrayCollection") {
			out.dataProvider = createDataProvider(item)
		} else {
			console.error("list中暂时不支持其它的类型",item, item.node, item.attributes)
		}
	}
	let itemName = obj.attributes.itemRendererSkinName;
	if (itemName) {
		let itemSkin = itemRendererMap[itemName];
		let itemObj = {};
		parseObj(itemSkin, itemObj)
		out.itemRenderer = itemObj
	}
}

// 创建布局
function createLayout(obj) {
	let out = {};
	let name = obj.children[0].name;
	name = name.replace("e:", "")
	out.type = name;
	Object.assign(out, obj.children[0].attributes)
	return out;
}

// 创建数据源
function createDataProvider(obj) {
	let dataProvider = [];
	let children = obj.children[0];
	if (children) {
		let subChildren = children.children;
		let count = subChildren ? subChildren.length : 0;
		for (let i = 0; i < count; i++) {
			let obj = {};
			dataProvider.push(Object.assign(obj, subChildren[i].attributes))
		}
	}
	return dataProvider;
}

// 复制通用属性
function copyCommonProp(source, target) {
	if (source.id) {
		target.id = source.id;
	}
	if (source.name) {
		target.name = source.name;
	}
	if (+source.x && +source.x != 1) {
		target.x = +source.x;
	}
	if (+source.y && +source.y != 1) {
		target.y = +source.y;
	}
	if (+source.anchorOffsetX) {
		let width = +source.width;
		if (resMap[source.source]) {
			width = resMap[source.source].sourceW
		}
		target.anchorX =  +source.anchorOffsetX / width
	}	
	if (+source.anchorOffsetY) {
		let height = +source.height;
		if (resMap[source.source]) {
			height = resMap[source.source].sourceH
		}
		target.anchorY = +source.anchorOffsetY / height;
	}
	if (source.width) {
		target.width = source.width;
	}
	if (source.height) {
		target.height = source.height;
	}
	if (source.visible == "false") {
		target.visible = 0;
	}
	if (source.touchChildren) {
		target.interactive = true;
	}
	if (source.minWidth) {
		target.minWidth = source.minWidth;
	}
	if (source.minHeight) {
		target.minHeight = source.minHeight;
	}
	if (source.maxWidth) {
		target.maxWidth= source.maxWidth;
	}
	if (source.maxHeight) {
		target.maxHeight = source.maxHeight;
	}
}

// 得到节点的名字
function getNodeName(obj) {
	let name = obj.name;
	let index = name.indexOf(":");
	if (index > 0) {
		if (name.substr(0, 1) == "e") {
			name = name.slice(index + 1);
			if (NODE_MAP[name]) {
				name = NODE_MAP[name];
				if (!name) {
					console.error('不能解析egret定义的类:', name)
				}
			}
		} else {
			name = name.slice(index + 1);
		}
	}
	return name;
}

